package com.lvyq.myplayer.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.widget.RemoteViews
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.lifecycle.ViewModelProvider
import com.lvyq.myplayer.R
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.common.shared.PlayModeSharedPrefsManager
import com.lvyq.myplayer.common.shared.PlayingDownloadSharedPrefsManager
import com.lvyq.myplayer.database.PlayerDatabase
import com.lvyq.myplayer.model.cache.PlayCacheEntity
import com.lvyq.myplayer.model.common.EventPlayerViewModel
import com.lvyq.myplayer.model.current.CurrentPlayLstEntity
import com.lvyq.myplayer.model.history.PlayHistoryEntity
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.ui.activity.MainActivity
import com.lvyq.myplayer.util.ThreadUtil.runOnMainThread
import com.lvyq.myplayer.util.URLProviderUtils
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.URL
import java.util.UUID
import kotlin.random.Random


/**
 * 文件描述：AudioService
 * 作者：lvyq
 * 创建时间：2025-03-06
 * 修改时间：2025-03-06
 */
class AudioService: Service() {
    // 创建专用协程作用域
    private val playHistoryDao by lazy { PlayerDatabase.getDatabase(this).playHistoryDao() }
    private val playCacheDao by lazy { PlayerDatabase.getDatabase(this).playCacheDao() }

    val FROM_PRE=1
    val FROM_NEXT=2
    val FROM_PLAY=3
    val FROM_CONTENT=4

    var AudioNotification:Notification? = null

    //当前播放的歌曲num
    var data:SongInfoData?=null
    //歌曲列表下标
    var position:Int = 0;

    var mediaPlayer:MediaPlayer?=null
    //歌曲集合
    var list:ArrayList<SongInfoData>? =null

    //通知栏
    var notificationManager:NotificationManager?=null

     companion object{
        val PLAY_MODE_ALL=1
        val PLAY_MODE_SINGLE=2
        val PLAY_MODE_RANDOM=3
    }
    //默认顺序全部播放
    var PLAY_MODE=PLAY_MODE_ALL

    val binder by lazy { AudioBinder() }
    //创建
    @SuppressLint("SuspiciousIndentation")
    override fun onCreate() {
        super.onCreate()
        //获取模式，获取不到时默认值为1
        PLAY_MODE= PlayModeSharedPrefsManager.getMode(this)
    }

    //执行startService时调用 ,在onStartCommand获取intent值。多次创建Service时会多次调用onStartCommand方法，所以在onStartCommand中获取值好些
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        //判断Service 进入方式
        var from = intent?.getIntExtra("from", -1)
        var inPosition = intent?.getIntExtra("position",-1)
        var currentSongData: SongInfoData? = intent?.getParcelableExtra("data")

        //初始数据，与flow  initAudioPlayLst 数据配合更新
        list=MainAudioSharedPrefsManager.getSongInfoList(this@AudioService)

        when(from){
            FROM_PRE->{binder.preMusicPlay()}
            FROM_NEXT->{binder.nextMusicPlay()}
            FROM_PLAY->{
                binder.updPlayState(false)
            }
            FROM_CONTENT->{
                notifyUpdateUI()
            }
            else -> {
                //从条目点击进入
                //当前播放音乐与将要播放的音乐不一致时。并且id不一致时
                var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this@AudioService)
                if (position!= inPosition
                    || !data?.position.toString() .equals(currentAudioPosition)//同一首歌不同position的情况
                    || data?.id != currentSongData?.id //不同歌曲，同一个position的情况
                ){
                    position=inPosition?:0
                    binder.play()
                }

            }
        }
        //START_STICKY 粘性的 如果service强制杀死后，会尝试重新启动Service 不会传递原来的intent 此时intent为null
        //START_NOT_STICKY 非粘性的 如果service强制杀死后不会尝试重新启动
        //START_REDELIVER_INTENT  如果service强制杀死后会尝试重新启动，并传递原来的initent
       // return super.onStartCommand(intent, flags, startId)
        return Service.START_NOT_STICKY
    }



    //多次创建Servie 只会调用一次onBind函数，在该函数中回去intent值不合适
    override fun onBind(intent: Intent?): IBinder? {

        return binder
    }

    /**
     * 通过Binder将Activity与Service串联起来，实现播放交互
     *
     * inner 内部类，调用data
     */
   inner class AudioBinder : Binder() ,IService, MediaPlayer.OnPreparedListener,
         MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
        fun getService(): AudioService = this@AudioService

        fun play() {
            try {
                data = list?.get(position)
            }catch (e:Exception){
                return
            }

            Log.i("AudioService","AudioService->播放(play)->"+data?.title)
            if (data!=null){
                //判断是否存在缓存数据，存在则使用缓存数据播放
                var downloadAudioCacheDir = File(cacheDir.absolutePath+"/music")
                val audioFileName = data?.id.toString()+".mp3"
                val audioFile = File(downloadAudioCacheDir, audioFileName)
                // 检查文件是否已存在
                if (audioFile.exists()) {
                    data?.song=audioFile.path
                    initializeMediaPlayer(data)
                }else{
                    if (data?.reNum?:1<0){
                        //固定可用的音源，直接播放
                        initializeMediaPlayer(data)
                    }else{
                        val client = OkHttpClient()
                        val request = Request.Builder()
                            .url(URLProviderUtils.DoMain + "song/reUpdSong?id=" + data?.id)
                            .build()

                        // 改为异步请求
                        client.newCall(request).enqueue(object : Callback {
                            override fun onResponse(call: Call, response: Response) {
                                val newSongUrl = response.body?.string()
                                println(">>>>>>>>>>>"+newSongUrl+"["+data?.id+"_"+data?.title+"("+position+")]")
                                data?.song = newSongUrl

                                // 需要在主线程更新UI或操作MediaPlayer
                                Handler(Looper.getMainLooper()).post {
                                    initializeMediaPlayer(data)
                                }
                            }

                            override fun onFailure(call: Call, e: IOException) {
                                // 错误处理
                                Log.e("MediaPlayerService", "Request failed: ${e.message}")
                                /* nextMusicPlay()*/
                            }
                        })
                    }
                }




            }


        }

        // 提取媒体播放器初始化逻辑
        public fun initializeMediaPlayer(data:SongInfoData?) {
            if (mediaPlayer != null) {
                mediaPlayer?.reset()
                mediaPlayer?.release()
                mediaPlayer = null
            }

            mediaPlayer = MediaPlayer().apply {
                try {
                    setDataSource(data?.song)
                   // setOnErrorListener(this@AudioBinder)
                    setOnPreparedListener(this@AudioBinder)
                    setOnCompletionListener(this@AudioBinder)
                    prepareAsync()
                } catch (e: Exception) {
                    nextMusicPlay()
                    Log.e("MediaPlayerServicePlay", e.message.toString())
                }
            }
        }



        //更新播放状态，是否强制播放并返回
        override fun updPlayState(isStart:Boolean): Boolean? {
            var playState = mediaPlayer?.isPlaying()
            if (isStart){
                //非播放页点击，而是从列表页跳入 强制播放
                playState=false
            }
            playState?.let {
                if (it){
                   //播放中，  暂停
                   pause()
                }else{
                    //暂停，  播放
                    start()
                }
            }
            //将改变后的状态返回
            return mediaPlayer?.isPlaying()
        }

        /**
         * 获取总进度
         */
        override fun getTotalDuration(): Int? {
          return mediaPlayer?.duration
        }

        /**
         * 获取当前进度
         */
        override fun getProgress(): Int? {
           return mediaPlayer?.currentPosition?:0
        }

        /**
         * 跳转进度 播放
         */
        override fun seekTo(progress: Int) {
          mediaPlayer?.seekTo(progress)
        }



        /**
         * 播放下一曲
         */
        override fun palyNextAudio() {
            when(PLAY_MODE){
                //全部循环播放
                PLAY_MODE_ALL-> {
                    val totalNum = list?.size?:0
                    //根据newNum获取值
                    list?.let {
                        position=(position+1)%totalNum
                    }
                }
              PLAY_MODE_SINGLE->{}
                PLAY_MODE_RANDOM->{
                    list?.let {
                        if (it.size==1){
                            position=0
                        }else{
                            position = Random.nextInt(it.size-1)
                        }

                    }

                }
            }
            play()

        }


        /**
         * 更新播放模式并返回最新的模式
         */
        override fun setPlayMode() {
            when(PLAY_MODE){
                PLAY_MODE_ALL->PLAY_MODE=PLAY_MODE_SINGLE
                PLAY_MODE_SINGLE->PLAY_MODE=PLAY_MODE_RANDOM
                PLAY_MODE_RANDOM->PLAY_MODE=PLAY_MODE_ALL
            }
            //保存播放模式
            PlayModeSharedPrefsManager.putMode(this@AudioService,PLAY_MODE)
        }

        /**
         * 获取播放模式
         */

        override fun getPlayMode(): Int {
            return PLAY_MODE
        }

        /**
         * 播放上一曲
         */
        override fun preMusicPlay() {
            list?.let {
                when(PLAY_MODE){
                    //随机模式
                    PLAY_MODE_RANDOM->{
                        if (it.size==1){
                            position=0
                        }else{
                            position = Random.nextInt(it.size-1)
                        }
                    }
                    else->{
                        //第一首歌曲
                        if (position==0){
                            position=it.size-1
                        }else{
                            position= position.minus(1)
                        }
                    }
                }

            }
            binder.play()
        }

        /**
         * 播放下一曲
         */

        override fun nextMusicPlay() {
            list?.let {
                when(PLAY_MODE){
                    //随机模式
                    PLAY_MODE_RANDOM->{
                        if (it.size==1){
                            position=0
                        }else{
                            position = Random.nextInt(it.size-1)
                        }
                    }
                    else->{
                        if (position==it.size-1){
                            position=0
                        }else{
                            position=position+1
                        }
                    }

                }
            }
           binder.play()
        }



        /**
         * 指定播放
         */
        override fun musicPlayPosition(pos: Int,currentSongData: SongInfoData?) {
            //当前播放音乐与将要播放的音乐不一致时。并且id不一致时
            var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this@AudioService)
            if (position!= pos
                || !data?.position.toString() .equals(currentAudioPosition)//同一首歌不同position的情况
                || data?.id != currentSongData?.id //不同歌曲，同一个position的情况
            ){
                position=pos?:0
                binder.play()
            }
        }

        override fun getPlayList(): ArrayList<SongInfoData>? {
            //从数据库中获取
            return list
        }



        override fun getPosition(): Int? {
            return position
        }

        /**
         * 获取播放状态
         */
        override fun getPlayState(): Boolean {
            return mediaPlayer?.isPlaying?:false
        }

        override fun stop() {
            pause()
        }

        override fun initAudioPlayLst(playList: ArrayList<SongInfoData>) {
            list=playList
        }

        override fun updateCurrentPosition(currentPosition: Int) {
            position=currentPosition
        }

        /**
         * 指定播放的单曲创建的方法
         */
        override fun playForDelCurrent(audioInfo: SongInfoData,cureentPosition:Int) {
            data=audioInfo
            position=cureentPosition
            if (data != null) {
                //判断是否存在缓存数据，存在则使用缓存数据播放
                var downloadAudioCacheDir = File(cacheDir.absolutePath + "/music")
                val audioFileName = data?.id.toString() + ".mp3"
                val audioFile = File(downloadAudioCacheDir, audioFileName)
                // 检查文件是否已存在
                if (audioFile.exists()) {
                    data?.song = audioFile.path
                    initializeMediaPlayer(data)
                } else {
                    if (data?.reNum ?: 1 < 0) {
                        //固定可用的音源，直接播放
                        initializeMediaPlayer(data)
                    } else {
                        val client = OkHttpClient()
                        val request = Request.Builder()
                            .url(URLProviderUtils.DoMain + "song/reUpdSong?id=" + data?.id)
                            .build()

                        // 改为异步请求
                        client.newCall(request).enqueue(object : Callback {
                            override fun onResponse(call: Call, response: Response) {
                                val newSongUrl = response.body?.string()
                                data?.song = newSongUrl

                                // 需要在主线程更新UI或操作MediaPlayer
                                Handler(Looper.getMainLooper()).post {
                                    initializeMediaPlayer(data)
                                }
                            }

                            override fun onFailure(call: Call, e: IOException) {
                                // 错误处理
                                Log.e("MediaPlayerService", "Request failed: ${e.message}")
                            }
                        })
                    }
                }
            }
        }

        override fun clearService(audioInfo: SongInfoData) {
            if (mediaPlayer != null) {
                mediaPlayer?.reset()
                mediaPlayer?.release()
                mediaPlayer = null
            }
            EventPlayerViewModel.updateCurrentPlaySong(audioInfo)
            MainAudioSharedPrefsManager.saveSongInfo(this@AudioService,audioInfo)
        }

        /**
         * 播放监听
         */
        @SuppressLint("SuspiciousIndentation")
        override fun onPrepared(mp: MediaPlayer?) {
            //播放
          var playState=  MainAudioSharedPrefsManager.getPlayState(this@AudioService)
            playState?.let {
                if (it.equals("true")){
                    start()
                }
            }

            //通知界面更新
            notifyUpdateUI()

            //显示通知
            showNotification()

            // 播放记录存储 IO中处理。避免UI堵塞
            CoroutineScope(Dispatchers.IO).launch {

                //缓存
                var playingDownloadState = PlayingDownloadSharedPrefsManager.getState(this@AudioService)
                if (playingDownloadState){
                    startSavingPic(data)
                    startSavingAudio(data)
                }
                val currentTimeStamp = System.currentTimeMillis()
                data?.let {
                        var historyEntity=  playHistoryDao.getPlayHistoryByBusinessKeyAndType(it.id, 1)
                        if (historyEntity!=null){
                            historyEntity.updateTime=currentTimeStamp
                            historyEntity.playCount=historyEntity.playCount+1
                            playHistoryDao.updatePlayHistory(historyEntity)
                        }else{
                            val newEntry = PlayHistoryEntity(
                                title=it.title?:"",
                                businessKey = it.id,
                                singer = it.singer,
                                bgImg = it.bgImg?:"",
                                url = it.song,
                                lrc = it.lrc,
                                singerId = it.singerId,
                                publishDate = it.publishDate,
                                albumId = it.albumId,
                                albumName = it.albumName,
                                createTime = currentTimeStamp,
                                updateTime = currentTimeStamp,
                                totalDuration = mediaPlayer?.duration,
                                playCount = 1,
                                type = 1)
                                playHistoryDao.insertPlayHistory(newEntry)
                        }

                }

            }

        }

        /**
         * setOnCompleteListener 监听
         * 歌曲播放完毕回调
         */
        override fun onCompletion(mp: MediaPlayer?) {
            //播放下一曲
            palyNextAudio()
        }

        /**
         * 音源破损
         */
        override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
            runOnMainThread{
                Toast.makeText(this@AudioService,"请稍等,搜索可用音源中..",Toast.LENGTH_SHORT).show()
            }
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(URLProviderUtils.DoMain + "song/reUpdSong?id=" + data?.id)
                .build()

            // 改为异步请求
            client.newCall(request).enqueue(object : Callback {
                override fun onResponse(call: Call, response: Response) {
                    val newSongUrl = response.body?.string()
                    data?.song = newSongUrl

                    // 需要在主线程更新UI或操作MediaPlayer
                    Handler(Looper.getMainLooper()).post {
                        initializeMediaPlayer(data)
                    }
                }

                override fun onFailure(call: Call, e: IOException) {
                    // 错误处理
                    Log.e("MediaPlayerService", "Request failed: ${e.message}")
                    /* nextMusicPlay()*/
                }
            })
            return true
        }

    }


    //暂停
    private fun pause(){
        Log.i("AudioService","AudioService->暂停(pause)->"+data?.title)
        mediaPlayer?.pause()

        EventPlayerViewModel.updatePlayState(false)
        MainAudioSharedPrefsManager.savePlayState(this,"false");
        //设置通知栏播放状态图标
        AudioNotification?.contentView?.setImageViewResource(R.id.play_music,R.mipmap.notify_start)
        //通知刷新
        notificationManager?.notify(1,AudioNotification)
    }


    private fun start(){
        Log.i("AudioService","AudioService->播放(start)->"+data?.title)

        mediaPlayer?.start()

        EventPlayerViewModel.updatePlayState(true)
        MainAudioSharedPrefsManager.savePlayState(this,"true");
        //设置通知栏播放状态图标
        AudioNotification?.contentView?.setImageViewResource(R.id.play_music,R.mipmap.notify_stop)
        //通知刷新
        notificationManager?.notify(1,AudioNotification)
    }

    /**
     * 显示通知
     */
    private fun showNotification() {
        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        AudioNotification = getNotification()

        if (data?.bgImg!=null || !"".equals(data?.bgImg)){
            Picasso.with(this).load(data?.bgImg).into(object: Target {
                override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
                    bitmap?.let {
                        //设置通知栏播放状态图标
                        AudioNotification?.contentView?.setImageViewBitmap(R.id.img,it)                    }
                }
                override fun onBitmapFailed(errorDrawable: Drawable?) {
                }
                override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
                }
            })
        }
        //初始化图标，默认暂停图标
        AudioNotification?.contentView?.setImageViewResource(R.id.play_music,R.mipmap.notify_stop)
        notificationManager?.notify(1,AudioNotification)
}
    /**
     *  创建Notification
     */
    private fun getNotification(): Notification? {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "channel_id_audioPlay"
            val channelName = "AudioPlayChannel"
            val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)//静音通知
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }

        var notification = NotificationCompat.Builder(this@AudioService,"channel_id_audioPlay")
            .setTicker("正在播放歌曲${data?.title}")
            .setSmallIcon(R.mipmap.yinle_1) //通知图标必需
            //自定义通知
            .setCustomContentView(getRemoteViews())
            .setWhen(System.currentTimeMillis())
                //通知优先级
            .setPriority(NotificationCompat.PRIORITY_LOW) //没有声音
            .setOngoing(true)//设置不能滑动删除通知
            .setContentIntent(getPendingIntent())//通知栏点击事件
            .build()
        return notification
    }

    /**
     * 通知栏点击事件
     */
    private fun getPendingIntent():PendingIntent {
        val intentMain = Intent(this@AudioService, MainActivity::class.java)
        intentMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        //跳转到播放页面
        val intentAudio = Intent(this@AudioService, com.lvyq.myplayer.ui.activity.AudioPlayerActivity::class.java)
        intentAudio.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        intentAudio.putExtra("from",FROM_CONTENT)
        //FLAG_UPDATE_CURRENT 更新新通知
        val intentLst = arrayOf(intentMain,intentAudio)
        val pendingIntent = PendingIntent.getActivities(this@AudioService,FROM_CONTENT,intentLst,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
        return pendingIntent
    }


    //自定义通知栏
    private fun getRemoteViews(): RemoteViews? {
        val remoteViews = RemoteViews(packageName, R.layout.notification)
        //修改标题和内容
        remoteViews.setTextViewText(R.id.title,data?.title)
        remoteViews.setTextViewText(R.id.singer,data?.singer)
        //处理上一曲，下一曲，状态点击事件
        remoteViews.setOnClickPendingIntent(R.id.pre_music,getPrePendingIntent())
        remoteViews.setOnClickPendingIntent(R.id.play_music,getPlayPendingIntent())
        remoteViews.setOnClickPendingIntent(R.id.next_music,getNextPendingIntent())

        return  remoteViews
    }

    /**
     *  状态栏-下一曲点击事件
     */
    private fun getNextPendingIntent(): PendingIntent? {
        val intent = Intent(this@AudioService,AudioService::class.java)
        intent.putExtra("from",FROM_NEXT)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        //FLAG_UPDATE_CURRENT 更新新通知
        val pendingIntent = PendingIntent.getService(this@AudioService,FROM_NEXT,intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE )
        return pendingIntent
    }
    /**
     *  状态栏-上一曲点击事件
     */
    private fun getPrePendingIntent(): PendingIntent? {
        val intent = Intent(this@AudioService,AudioService::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        intent.putExtra("from",FROM_PRE)
        //FLAG_UPDATE_CURRENT 更新新通知
        val pendingIntent = PendingIntent.getService(this@AudioService,FROM_PRE,intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE )
        return pendingIntent
    }
    /**
     * 状态栏-状态点击事件
     */
    private fun getPlayPendingIntent(): PendingIntent? {

        val intentAudio = Intent(this@AudioService,AudioService::class.java)
        intentAudio.putExtra("from",FROM_PLAY)
        intentAudio.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        //FLAG_UPDATE_CURRENT 更新新通知
        val pendingIntent = PendingIntent.getService(this@AudioService,FROM_PLAY,intentAudio,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE )
        return pendingIntent
    }



    /**
     * 通知界面更新、通知主页界面更新
     */
    private fun notifyUpdateUI() {

        data?.let {

            //当前播放id。用于标识处理正在播放的img状态，以及获取正在播放的音乐，在播放栏中,目前在播放列表中，使用了此处存储的值
            MainAudioSharedPrefsManager.saveCurrentAudioPosition(this@AudioService,data?.position.toString())
            //记录当前播放音乐。用于退出应用后继续播放，暂时不存储播放进度。再次进入后从头播放
            MainAudioSharedPrefsManager.saveSongInfo(this@AudioService,data)
            //通知
           // it.position=position
            //用于全局通知歌曲切换,主要用于更新底部播放栏的信息
            EventPlayerViewModel.updateCurrentPlaySong(it)
            //当前正在播放的音乐id，用于通知更新播放图标
            EventPlayerViewModel.updateCurrentPlaySongId(data?.position?:-1)

            Log.i("AudioService","播放歌曲通知(notifyUpdateUI):"+data?.position+"_"+data?.title)
        }

    }



    override fun onDestroy() {
        super.onDestroy()
        notificationManager?.cancelAll()
    }


    // 开始保存音频到文件
    private fun startSavingAudio(data: SongInfoData?) {
        var downloadAudioCacheDir = File(cacheDir.absolutePath+"/music")
        val audioFileName = data?.id.toString()+".mp3"
        val outputFile = File(downloadAudioCacheDir, audioFileName)

        // 检查文件是否已存在
        if (outputFile.exists()) {
            return
        }

        Thread {
            try {
                // 确保目录存在，如果不存在则创建
                if (!downloadAudioCacheDir.exists()) {
                    downloadAudioCacheDir.mkdirs()
                }
                val url = URL(data?.song)
                val connection = url.openConnection()
                connection.connect()

                val inputStream = connection.getInputStream()
                val outputStream = FileOutputStream(outputFile)

                val buffer = ByteArray(1024)
                var bytesRead: Int

                while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                    outputStream.write(buffer, 0, bytesRead)
                }

                outputStream.flush()
                outputStream.close()
                inputStream.close()
                // 本地缓存记录
                CoroutineScope(Dispatchers.IO).launch {

                    val currentTimeStamp = System.currentTimeMillis()
                    data?.let {
                        var Entity=  playCacheDao.getPlayCacheByBusinessKeyAndType(it.id, 1)
                        if (Entity == null){
                            val newEntry = PlayCacheEntity(
                                title=it.title?:"",
                                businessKey = it.id,
                                singer = it.singer,
                                bgImg = it.bgImg?:"",
                                url = it.song,
                                lrc = it.lrc,
                                singerId = it.singerId,
                                publishDate = it.publishDate,
                                albumId = it.albumId,
                                albumName = it.albumName,
                                createTime = currentTimeStamp,
                                updateTime = currentTimeStamp,
                                totalDuration = mediaPlayer?.duration,
                                playCount = 1,
                                type = 1)
                            playCacheDao.insertPlayCache(newEntry)
                        }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }.start()
    }
    private fun startSavingPic(data: SongInfoData?) {
        var downloadPicCacheDir = File(cacheDir.absolutePath + "/pic")
        val picFileName = data?.id.toString()+".png"
        val outputFile = File(downloadPicCacheDir, picFileName)

        // 检查文件是否已存在
        if (outputFile.exists()) {
            return
        }

        Thread {
            try {
                if (!downloadPicCacheDir.exists()) {
                    downloadPicCacheDir.mkdirs() // 创建多级目录
                }
                val url = URL(data?.bgImg)
                val connection = url.openConnection()
                connection.connect()

                val inputStream = connection.getInputStream()
                val outputStream = FileOutputStream(outputFile)

                val buffer = ByteArray(1024)
                var bytesRead: Int

                while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                    outputStream.write(buffer, 0, bytesRead)
                }

                outputStream.flush()
                outputStream.close()
                inputStream.close()
            } catch  (e: IOException) {
                e.printStackTrace()
            }
        }.start()
    }



}

